import { constantRoutes, asyncRoutes } from '@/router'

function hasPermission(permissions, route) {
	if (route.meta && route.meta.permissions) {
		return permissions.some((permission) => route.meta.permissions.includes(permission.action))
	} else {
		return true
	}
}

export function filterAsyncRoutes(routes, permissions) {
	const res = []
	routes.forEach((route) => {
		if (hasPermission(permissions, route)) {
			if (route.children) {
				route.children = filterAsyncRoutes(route.children, permissions)
			}
			res.push(route)
		}
	})

	return res
}

const state = {
	routes: [],
	addRoutes: [],
}

const mutations = {
	SET_ROUTES: (state, routes) => {
		state.addRoutes = routes
		state.routes = constantRoutes.concat(routes)
	},
}

const actions = {
	generateRoutes({ commit }, permissionsData) {
		return new Promise((resolve) => {
			let accessedRoutes
			if (permissionsData.length > 0) {
				accessedRoutes = filterAsyncRoutes(asyncRoutes, permissionsData)
				//console.log(asyncRoutes,permissionsData)
			} else {
				accessedRoutes = []
			}
			commit('SET_ROUTES', accessedRoutes)
			resolve(accessedRoutes)
		})
	},
}

export default {
	namespaced: true,
	state,
	mutations,
	actions,
}
